package chen.yi.component.mysql.check;

import chen.yi.component.common.exception.BizException;
import chen.yi.component.mysql.enums.TableErrorEnums;
import chen.yi.component.mysql.po.ForeignKeyPO;
import chen.yi.component.mysql.utils.TableAttrUtils;
import chen.yi.component.mysql.vo.system.ForeignKeyVO;

import java.util.List;

/**
 * 字段属性校验规则
 * @author huat
 **/
public final class ForeignKeyUtils extends BaseCheckUtils {
    private ForeignKeyUtils() {}
    /**
     * 校验字段是否合法
     * @param foreignKeyPOS 外键集合
     */
    public static void checkForeignKey(final List<ForeignKeyPO> foreignKeyPOS) {
        foreignKeyPOS.forEach(foreignKeyPO -> {
            checkName(foreignKeyPO.getForeignKeyName());
            checkWhen(foreignKeyPO.getWhenDelete());
            checkWhen(foreignKeyPO.getWhenUpdate());
        });
    }

    /**
     * 校验外键名是否合法
     * @param fieldName 字段名
     */
    private static void checkName(final String fieldName) {
        if (!NAME_PATTERN.matcher(fieldName).matches() || RESERVED_WORDS.contains(fieldName.toUpperCase())) {
            throw new BizException(TableErrorEnums.FOREIGN_NAME.getCode(), String.format(TableErrorEnums.FOREIGN_NAME.getMessage(),fieldName));
        }
    }
    /**
     * 校验删除时/修改时逻辑
     * @param when 操作时
     */
    private static void checkWhen(final String when) {
        //获取字段类型对象
        ForeignKeyVO foreignKey = TableAttrUtils.getForeignKey();
        List<String> constraint = foreignKey.getConstraint();
        if(!constraint.contains(when)){
            throw new BizException(TableErrorEnums.WHEN_NAME.getCode(), String.format(TableErrorEnums.WHEN_NAME.getMessage(),when));
        }
    }

}
